class BallotNotFound < Exception
end

class BallotAlreadyUsed < Exception
end

class Ballot < ActiveRecord::Base

  hobo_model

  belongs_to :user
  belongs_to :election, :counter_cache => true
  
  attr_accessible :user_id, :election_id
  
  # --- Validation --- #
  
  validates_presence_of :user_id, :election
  validates_uniqueness_of :election_id, :scope => :user_id
  validates_inclusion_of :cast, :in => [true, false], :allow_nil => true

  # --- Hobo Permissions --- #

  def creatable_by?(creator)
    false
  end

  def updatable_by?(updater, new)
    false
  end

  def deletable_by?(deleter)
    false
  end

  def viewable_by?(viewer, field)
    false
  end

  # --- Methods --- #
  
  def self.new_from_params(user,election)
    ballot = Ballot.new
    ballot.user = user
    ballot.election = election
    ballot
  end
  
  def self.find_valid(user,election)
    ballot = Ballot.find(:first, :conditions => ["cast = ? AND election_id = ? AND user_id = ?", false, election.id, user.id])
    raise BallotNotFound if ballot.nil?
    raise BallotAlreadyUsed if ballot.cast?
    ballot
  end
  
  def cast!
    raise BallotAlreadyUsed if cast
    # Wouldn't work with standard assignment
    write_attribute :cast, true
    save!
    true
  end
  
end
